package version

import (
	"fmt"
	"runtime"
)

// Info 版本信息
type Info struct {
	ServiceName string // 服务名称
	Version     string // 版本号
	BuildTime   string // 构建时间
	GitCommit   string // Git提交哈希
	GoVersion   string // Go版本
	Builder     string // 构建者
	Platform    string // 运行平台
}

// 全局版本信息，由编译器注入
var (
	version   string
	buildTime string
	gitCommit string
	goVersion string
	builder   string
)

// NewInfo 创建版本信息实例
func NewInfo(serviceName string) Info {
	return Info{
		ServiceName: serviceName,
		Version:     version,
		BuildTime:   buildTime,
		GitCommit:   gitCommit,
		GoVersion:   goVersion,
		Builder:     builder,
		Platform:    fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH),
	}
}

// String 返回版本信息的字符串表示
func (i Info) String() string {
	return fmt.Sprintf(
		"%s version %s\n"+
			"  Git commit: %s\n"+
			"  Build time: %s\n"+
			"  Go version: %s\n"+
			"  Platform: %s\n"+
			"  Builder: %s",
		i.ServiceName,
		i.Version,
		i.GitCommit,
		i.BuildTime,
		i.GoVersion,
		i.Platform,
		i.Builder,
	)
}

// Map 返回版本信息的map表示
func (i Info) Map() map[string]string {
	return map[string]string{
		"serviceName": i.ServiceName,
		"version":     i.Version,
		"buildTime":   i.BuildTime,
		"gitCommit":   i.GitCommit,
		"goVersion":   i.GoVersion,
		"platform":    i.Platform,
		"builder":     i.Builder,
	}
}
